package com.atguigu.cloud.common.security;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.regex.Pattern;

/**
 * 输入验证工具类
 */
@Component
public class InputValidator {

    // 银行卡号正则（16-19位数字）
    private static final Pattern BANK_CARD_PATTERN = Pattern.compile("^\\d{16,19}$");
    
    // 邮箱正则
    private static final Pattern EMAIL_PATTERN = Pattern.compile(
        "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
    );
    
    // SQL注入关键词
    private static final String[] SQL_INJECTION_KEYWORDS = {
        "select", "insert", "update", "delete", "drop", "create", "alter",
        "exec", "execute", "union", "script", "javascript", "vbscript",
        "onload", "onerror", "onclick", "<script", "</script>", "eval("
    };

    /**
     * 验证银行卡号
     */
    public boolean isValidBankCard(String cardNumber) {
        if (!StringUtils.hasText(cardNumber)) {
            return false;
        }
        return BANK_CARD_PATTERN.matcher(cardNumber.trim()).matches();
    }

    /**
     * 验证邮箱地址
     */
    public boolean isValidEmail(String email) {
        if (!StringUtils.hasText(email)) {
            return false;
        }
        return EMAIL_PATTERN.matcher(email.trim()).matches();
    }

    /**
     * 检查SQL注入和XSS攻击
     */
    public boolean containsMaliciousContent(String input) {
        if (!StringUtils.hasText(input)) {
            return false;
        }
        
        String lowerInput = input.toLowerCase();
        for (String keyword : SQL_INJECTION_KEYWORDS) {
            if (lowerInput.contains(keyword)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 清理和转义输入内容
     */
    public String sanitizeInput(String input) {
        if (!StringUtils.hasText(input)) {
            return input;
        }
        
        return input.trim()
                .replaceAll("<", "&lt;")
                .replaceAll(">", "&gt;")
                .replaceAll("\"", "&quot;")
                .replaceAll("'", "&#x27;")
                .replaceAll("/", "&#x2F;");
    }

    /**
     * 验证字符串长度
     */
    public boolean isValidLength(String input, int maxLength) {
        return StringUtils.hasText(input) && input.length() <= maxLength;
    }
}